package com.ruoyi.system.interAttr.attr;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.UUIDGenerator;
import com.ruoyi.system.interAttr.domain.GamesRes;
import com.ruoyi.system.interAttr.domain.InterAttrRes;
import com.ruoyi.system.interAttr.domain.InterServerRes;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.dto.HttpUtil;
import com.ruoyi.system.utils.AliUtils;
import com.ruoyi.system.utils.MultipartFileUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 密码游戏列表没有接口
 *
 * 等对面开发人员写好   2024 06 27
 *
 */
@Slf4j
@Service
public class MONITAOHHAttr implements AdapterAttr {

    public static String uploadAliyun(MultipartFile file, String fileName) throws IOException {
        // 1 获取上传需要的固定值
        String endpoint ="oss-cn-shenzhen.aliyuncs.com";      //你的站点
        String accessKeyId = "STS.NUBVqC1Wh4K77fLMYKmSiRZA9";
        String accessKeySecret = "5Jy6mpqbPn8B1v7nMZFC729LpCUuw6CHcZMPrtqYcMno";
        String bucketName = "shenzhenbucket01";       //你的bucket_name
        //外面获取文件输入流，最后方便关闭
        InputStream in = file.getInputStream();
        try {
            //2 创建OssClient对象
            OSS ossClient =new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
            //3 获取文件信息，为了上传
            // meta设置请求头
            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentType("image/jpg");
            //4 设置知道文件夹
            ossClient.putObject(bucketName,fileName,in, meta);
            //5 关闭ossClient
            ossClient.shutdown();
            //6 返回上传之后地址，拼接地址
            String uploadUrl = "https://"+bucketName+"."+endpoint+"/"+fileName;
            return uploadUrl;
        }catch(Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            in.close();
        }
    }


    @SneakyThrows
    public static void main(String[] args) {
        String img = "https://file.kejinlianmeng.com/temp/202410/25/15/2159LE2R12tt.jpg";
        byte[] bytes = AliUtils.downloadPicture(img);
        String name = img.substring(img.lastIndexOf("."));
        MultipartFile multipartFile = MultipartFileUtil.getMultipartFile(name, bytes);
//        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//        // yuy76t5rew01.jpg
//        // 获取文件名称
//        String fileName = multipartFile.getOriginalFilename();
//        fileName = "goodsPublish/" + uuid + fileName;
//        uploadAliyun(multipartFile,fileName);
////        String ossConfig = getOssConfig(salePartner);
////        String data = JSONObject.parseObject(ossConfig).getString("data");
////        String bucket = JSONObject.parseObject(data).getString("bucket");
////        String viewDomain = JSONObject.parseObject(data).getString("viewDomain");
        String endpoint = "oss-cn-shenzhen.aliyuncs.com";
//        String credentials = JSONObject.parseObject(data).getString("Credentials");
        String accessKeyId = "STS.NTLPkXbRnovuUfWcewQNxW2wV";
        String accessKeySecret = "5XPdc7cKYHodzuVWuLAbCHeZkE5K3HHLDCiVtR9oSjp4";
        String securityToken = "CAIS2AJ1q6Ft5B2yfSjIr5f5G9Hsj41P2LSeV0Dmh2UiXcFUuPfctDz2IHxLeXZoBO4dv/0wm29Q6PYTlrt4T55IQ1DzcMp8t8wKrFL6PNSZCVd7e21e2vOfAmG2J0PR/q27OpfULr70fvOqdCq39Etayqf7cjOPRkGsNYbz57dsctUQWHvTD1MEfqA0QDFvs8gHL3DcGO+wOxrx+ArqAVFvpxB3hBEUi8394LXFtkGG0QCllbJF/dSpe8X4VaQ2YscjCeXS9fdta6/M3BRX7xV376pshMRGg2yb4YzCWwQPuETfbLWLqoM/fRUKb6w7CrNCq+Pnifp7t+rcmoL60R9ROvtPVCDSVDJrJVt20k7D3L8YAlWbUxylurjnXhIl7oa4loc1HrfragiMW75hNDRoB5hzZuOr9FDDZg2iSaaB0qEy2Jp8wV8iVRImjfXH7z0xtU6uVVXvMStAXxqAAXXDDBTI/3uiH9m4xHlEIjRoQ68/qGivocgJ40XB3efU+u6CwbFxD2OdYGbAehNUS+YpYmpnQT7qc3jJLpVQ/jq76dHc6yKZ5lERs147wXQ7pQe5rG9X3IeRoBCZL1NNvrPhGrbYby73wjz4meT+bvXA2XQ7UFzBchU5auFNXMoqIAA=";

        String string = null;
        try {
            string = AliUtils.uploadFile(multipartFile,endpoint,accessKeyId,accessKeySecret,"shenzhenbucket01",securityToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<GamesRes> getGames(SalePartner salePartner) {
        String body = HttpRequest.get("https://api.taohaohaoapp.com/app/goods/game").execute().body();
        String result = MapUntils.unicodeToString(body);
        JSONObject resJson = JSONObject.parseObject(result);
        List<JSONObject> jsonObjects = JSONObject.parseArray(resJson.getString("data"), JSONObject.class);
        List<GamesRes> gamesResList = new ArrayList<>();

        for (JSONObject jsonObject : jsonObjects) {
            String business_types = jsonObject.getString("business_types");
            JSONArray jsonArray = JSONArray.parseArray(business_types);
            Object o = jsonArray.get(0);
            GamesRes gamesRes = new GamesRes();
            String id = jsonObject.getString("game_id")+","+JSONObject.parseObject(o.toString()).getString("business_id")+","+JSONObject.parseObject(o.toString()).getString("business_type");
            String name = jsonObject.getString("name");
            gamesRes.setId(id);
            gamesRes.setGameName(name);
            gamesResList.add(gamesRes);
        }
        return gamesResList;
    }

    @Override
    public List<InterServerRes> getServer(String gameId, SalePartner salePartner) {
        String body = HttpRequest.get("https://api.taohaohaoapp.com/app/game/partition?game_id="+gameId.split(",")[0]).execute().body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        List<JSONObject> data = JSONObject.parseArray(jsonObject.getString("data"), JSONObject.class);

        List<InterServerRes> interServerRes = new ArrayList<>();
        for (JSONObject datum : data) {
            InterServerRes interServer = new InterServerRes();
            interServer.setUuid(UUIDGenerator.generateUuid6());
            interServer.setId(datum.getString("partition_id"));
            interServer.setName(datum.getString("partition_name"));
            String son = datum.getString("son");
            if(StringUtils.isNotEmpty(son)) {
                List<InterServerRes> interServerRes1 = new ArrayList<>();
                List<JSONObject> jsonObjects2 = JSONObject.parseArray(son, JSONObject.class);
                for (JSONObject object : jsonObjects2) {
                    InterServerRes interServer1 = new InterServerRes();
                    String id1 = object.getString("id");
                    String title1 = object.getString("name");
                    interServer1.setUuid(UUIDGenerator.generateUuid6());
                    interServer1.setId(id1);
                    interServer1.setName(title1);
                    interServerRes1.add(interServer1);
                }
                interServer.setInterServerRes(interServerRes1);
            }
            interServerRes.add(interServer);
        }
        return interServerRes;
    }

    @Override
    public List<InterAttrRes> getPropety(String gameId, String type, SalePartner salePartner) {
        List<InterAttrRes> interAttrResList = new ArrayList<>();
        String url = "https://api.taohaohaoapp.com/app/goods/publish/properties";
        Map<String,String> params = new HashMap<>();
        Map<String,String> header = new HashMap<>();
        header.put("Authorization",salePartner.getSaleKey());
        params.put("game_id",gameId.split(",")[0]);
        params.put("business_id",gameId.split(",")[1]);
        params.put("business_type",gameId.split(",")[2]);
        String string = HttpUtil.doGet(url, params, header);
        String data = JSONObject.parseObject(string).getString("data");
        String items = JSONObject.parseObject(data).getString("items");
        List<JSONObject> data2 = JSONObject.parseArray(items, JSONObject.class);
        List<JSONObject> collect = new ArrayList<>();
        if (Objects.equals("1",type)){
            collect = data2.stream().filter(d -> d.getString("component").equals("select")||d.getString("component").equals("checkbox")).collect(Collectors.toList());
        }else if  (Objects.equals("2",type)){
            collect = data2.stream().filter(d -> d.getString("component").equals("select")||d.getString("component").equals("checkbox")).collect(Collectors.toList());
        }else if (Objects.equals("3",type)){
            collect = data2.stream().filter(d -> d.getString("component").equals("input_number")||d.getString("component").equals("input")).collect(Collectors.toList());
        }
        for (JSONObject object : collect) {
            InterAttrRes interAttrRes = new InterAttrRes();
            interAttrRes.setUuid(UUIDGenerator.generateUuid6());
            interAttrRes.setId(object.getString("property_id")+","+object.getString("component"));
            interAttrRes.setName(object.getString("property_name"));
            List<InterAttrRes> interAttrResList1 = new ArrayList<>();
            String val = object.getString("property_value");
            if(StringUtils.isNotEmpty(val)) {
                JSONArray jsonArray = JSONArray.parseArray(val);
                for (Object o : jsonArray) {
                    InterAttrRes interAttrRes1 = new InterAttrRes();
                    interAttrRes1.setUuid(UUIDGenerator.generateUuid6());
                    interAttrRes1.setId(o.toString());
                    interAttrRes1.setName(o.toString());
                    interAttrResList1.add(interAttrRes1);
                    interAttrRes.setInterServerRes(interAttrResList1);
                }
            }
            interAttrResList.add(interAttrRes);
        }
        return interAttrResList;
    }


    public static String getCover(Map<String,Object> params){


        log.info("通过Map.keySet遍历key和value：");

        StringBuffer resut = new StringBuffer();

        for (String key : params.keySet()) {

            log.info("key= "+ key + " and value= " + params.get(key));

            if (Objects.nonNull(params.get(key)) && StringUtils.isNotEmpty(String.valueOf(params.get(key)))){
                resut.append(params.get(key));
            }

        }
        return resut.toString();
    }
}